//
//  DSUnitExerciseToolbar.m
//  DSJY
//
//  Created by 冯华强 on 16/10/26.
//  Copyright © 2016年 dsjy. All rights reserved.
//  练习的工具条

#import "DSUnitExerciseToolbar.h"
#import "Masonry.h"
#import "NSString+Extension.h"
#import "UIColor+Extension.h"
#import "DSUnitListeningContent.h"

NSInteger minuteNum = 60;
@interface DSUnitExerciseToolbar ()
//倒计时
@property (strong, nonatomic) NSTimer *timer;
//分
@property (nonatomic, assign) NSInteger minute;
//秒
@property (nonatomic, assign) NSInteger seconds;
//一道题的题数
@property (nonatomic, assign) NSInteger pictures;
//花费秒数(在invalidate方法触发时会计算)
@property (nonatomic, assign, readwrite) NSInteger stime;
//分数(在invalidate方法触发时会计算)
@property (nonatomic, assign, readwrite) NSInteger score;
//题数
@property (nonatomic, assign) NSInteger exerciseTotalCount;
//播放音乐按钮
@property (nonatomic, weak, readwrite) UIButton *audioBtn;
//播放器
@property (nonatomic, strong, readwrite) AVAudioPlayer *player;
@end

@implementation DSUnitExerciseToolbar

#pragma mark - 懒加载
- (NSTimer *)timer
{
    if (_timer == nil) {
        _timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateTimerInfo:) userInfo:@"timer" repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
    return _timer;
}

#pragma mark - 系统回调
//初始化
+ (__kindof DSUnitExerciseToolbar *)toolbar
{
    return [[self alloc] init];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        //设置UI
        [self setupView];
    }
    return self;
}

- (void)setUnitExercise:(DSUnitExercise *)unitExercise
{
    _unitExercise = unitExercise;
    
    //去除正确和错误后，不做提示
//    BOOL isStory = unitExercise.exerciseType == DSUnitExerciseTypeStory;
//    self.rightButton.hidden = isStory;
//    self.wrongButton.hidden = isStory;
}

#pragma mark - 设置UI
- (void)setupView
{
    //时间
    UILabel *timeLabel = [[UILabel alloc] init];
    timeLabel.textColor = [UIColor color333333];
    timeLabel.text = @"00:00";
    [self addSubview:timeLabel];
    self.timeLabel = timeLabel;
    
    //答对题
    UIButton *rightButton = [[UIButton alloc] init];
    //hq_test
    rightButton.hidden = YES;
    [rightButton setImage:[UIImage imageNamed:@"icon_order_refundable"] forState:UIControlStateNormal];
    [rightButton setTitle:@"0" forState:UIControlStateNormal];
    rightButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [rightButton setTitleColor:[UIColor color333333] forState:UIControlStateNormal];
    [self addSubview:rightButton];
    self.rightButton = rightButton;
    
    //答错题
    UIButton *wrongButton = [[UIButton alloc] init];
    [wrongButton setImage:[UIImage imageNamed:@"icon_order_unrefundable"] forState:UIControlStateNormal];
    //hq_test
    wrongButton.hidden = YES;
    [wrongButton setTitle:@"0" forState:UIControlStateNormal];
    wrongButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [wrongButton setTitleColor:[UIColor color333333] forState:UIControlStateNormal];
    [self addSubview:wrongButton];
    self.wrongButton = wrongButton;
    
    //标题
    UILabel *titleLabel = [[UILabel alloc] init];
    //hq_test
    titleLabel.hidden = YES;
    titleLabel.text = @"0/0";
    titleLabel.textColor = [UIColor color333333];
    [self addSubview:titleLabel];
    self.titleLabel = titleLabel;
    
    //播放音频按钮
    UIButton *audioBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [audioBtn setImage:[UIImage imageNamed:@"sy"] forState:UIControlStateNormal];
    [audioBtn addTarget:self action:@selector(audioButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:audioBtn];
    self.audioBtn = audioBtn;
    
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.centerY.mas_equalTo(0);
    }];
    
    [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(80);
        make.centerY.mas_equalTo(0);
        make.width.mas_equalTo(80);
    }];
    
    [wrongButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(rightButton.mas_right);
        make.centerY.mas_equalTo(0);
        make.width.mas_equalTo(80);
    }];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
    }];
    
    [audioBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.width.mas_equalTo(50);
    }];
}

- (void)setupTitleIndex:(NSInteger)index totalCount:(NSInteger)totalCount
{
    //记录题数
    self.exerciseTotalCount = totalCount;
    //设置题数
    self.titleLabel.text = [NSString stringWithFormat:@"%ld/%ld", index, totalCount];
}

#pragma mark - 设置事件
- (void)startTimerWithMinute:(NSInteger)minute pictures:(NSInteger)pictures
{
    //记录分
    self.minute = minute;
    //分转秒
    self.seconds = minute * minuteNum;
    //记录题数
    self.pictures = pictures;
    //恢复正确题数和错误题数
    [self.rightButton setTitle:[NSString stringWithFormat:@"0"] forState:UIControlStateNormal];
    [self.wrongButton setTitle:[NSString stringWithFormat:@"0"] forState:UIControlStateNormal];
    //开始计时
    [self timer];
}

/** 更新信息 */
- (void)updateTimerInfo:(NSTimer *) timer
{
    if(--self.seconds <= 0){
        [self invalidate];
        
        if ([self.delegate respondsToSelector:@selector(unitExerciseToolbarDidTimerUp:)]) {
            [self.delegate unitExerciseToolbarDidTimerUp:self];
        }
    }
    
    self.timeLabel.text = [NSString timeformatFromSeconds:self.seconds];
}

//停止
- (void)invalidate
{
    [self.timer invalidate];
    self.timer = nil;
    
    if (self.pictures == 0) {
        return;
    }
    
    //计算花费的时间
    self.stime = self.minute * minuteNum - self.seconds;
    //计算分数
    BOOL isStory = self.unitExercise.exerciseType == DSUnitExerciseTypeStory;
    self.score = isStory ? 100 : ceilf([self.rightButton.currentTitle integerValue] / (CGFloat)(self.exerciseTotalCount * self.pictures) * 100);
}

- (void)setExercisDict:(NSMutableDictionary<NSNumber *,NSNumber *> *)exercisDict
{
    _exercisDict = exercisDict;
    
    NSInteger rightCount = 0;
    NSInteger wrongCount = 0;
    for (NSNumber *isRight in [exercisDict allValues]) {
        if ([isRight integerValue] == 0) {
            wrongCount++;
        }else{
            rightCount++;
        }
    }
    [self.rightButton setTitle:[NSString stringWithFormat:@"%ld", rightCount] forState:UIControlStateNormal];
    [self.wrongButton setTitle:[NSString stringWithFormat:@"%ld", wrongCount] forState:UIControlStateNormal];
}

#pragma mark - 音频按钮的处理
- (void)setListeningContent:(DSUnitListeningContent *)listeningContent
{
    _listeningContent = listeningContent;
    
    //hq_test
//    self.titleLabel.text = listeningContent.nameString;
    
    //停止－播放音频
    [self stopToPlayMusic];
}

#pragma mark - 设置事件
- (void)audioButtonClick
{
    if ([self.delegate respondsToSelector:@selector(unitExerciseToolbarDidAudioButtonClick:)]) {
        [self.delegate unitExerciseToolbarDidAudioButtonClick:self];
    }
}

- (void)stopToPlayMusic
{
    [self stopMusic];
    [self playMusic];
}

- (void)playMusic
{
    self.audioBtn.selected = YES;
    self.player = [XCYAudioTool playingMusicWithFileName:self.listeningContent.filePath isBundle:NO];
    //播放本地音乐
    [self.player play];
    self.player.delegate = self.delegate;
}

- (void)stopMusic
{
    self.audioBtn.selected = NO;
    self.player.delegate = nil;
//    [XCYAudioTool stopMusicWithFileName:self.listeningContent.filePath];
    [XCYAudioTool stopAllMusic];
}

@end
